# -*- coding: utf-8 -*-
# -*- coding: utf-8 -*-
from scpy.logger import get_logger
import os
import sys
from util.SCAWS import S3,SQS
import hashlib
import json
import datetime
from util.pgutil import PgUtil
import time

reload(sys)
sys.setdefaultencoding('utf-8')

logger = get_logger(__file__)

CURRENT_PATH = os.path.dirname(__file__)
if CURRENT_PATH:
    CURRENT_PATH = CURRENT_PATH + "/"

BUCKET_NAME = 'resume'
# KEY_PATH = 'src/2016/11/7'
KEY_PATH_ORIGIN = 'src/'
QUEUE_NAME = 'resume_trans'
MAX_NUM = 1000
s3 = S3()
sqs = SQS()
pgsql = PgUtil()
DAY = datetime.datetime.now().day
INSERT_RESUME_INFO = """
                          INSERT INTO resume(
                                  company_name,
                                  url,
                                  begin_time,
                                  end_time,
                                  release_time,
                                  sex,
                                  degree,
                                  working_years,
                                  dob,
                                  location,
                                  job_title,
                                  industry,
                                  detail,
                                  pre_company,
                                  next_company,
                                  school,
                                  major,
                                  expect_detail,
                                  education_detail
                          )  VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s);
                          """


def check_exist(url, companyName):
    sql = 'select * from resume where url=%s and company_name=%s'
    result = pgsql.select_sql(sql,(url,companyName))
    if result:
        return True
    else:
        return False


def main():
    while True:
        day = datetime.datetime.now().day
        if day != DAY:
            logger.info('new day! process ending')
            break
        result = sqs.receive_message(queue_name=QUEUE_NAME)
        if result:
            try:
                info = json.loads(result[0].get('Body'))
                _schoolList = list()
                _majorList = list()
                _url = info.get('url', '')
                _companyName = info.get('companyName', '')
                for item in info.get('educationInfo', []):
                    if item.get('school'):
                        _schoolList.append(item.get('school'))
                    if item.get('major'):
                        _majorList.append(item.get('major'))
                _values = [
                    info.get('companyName', ''),
                    info.get('url', ''),
                    info.get('beginDate', ''),
                    info.get('endDate', ''),
                    info.get('releaseDate', ''),
                    info.get('personalInfo').get('sex', ''),
                    info.get('personalInfo').get('degree', ''),
                    float(info.get('personalInfo').get('workingExperienceYear', 0)),
                    info.get('personalInfo').get('dob', ''),
                    info.get('personalInfo').get('location', ''),
                    info.get('jobTitle', ''),
                    info.get('industry', ''),
                    info.get('detail', ''),
                    info.get('preCompanyName') if info.get('preCompanyName') else '',
                    info.get('nextCompanyName') if info.get('nextCompanyName') else '',
                    _schoolList,
                    _majorList,
                    json.dumps(info.get('jobsExpectInfo', '')),
                    json.dumps(info.get('educationInfo', '')),
                ]
                if not check_exist(_url, _companyName):
                    pgsql.execute_insert_sql(INSERT_RESUME_INFO,_values)
                    logger.info('insert resume info into pgsql')
                else:
                    logger.warn('resume info already exist')
            except Exception,e:
                logger.error('insert resume info pgsql failed for %s'%str(e))
        else:
            logger.info('no message exist, sleeping 6s')
            time.sleep(6)


if __name__ == '__main__':
    main()